import React, { Component } from 'react'
import store, {actionCreator} from './store'
import {NavLink} from 'react-router-dom'

export default class Redux extends Component {
  constructor() {
    super();
    this.state = {
      age: 0,
      hobby: []
    }
  }
  changeAge() {
    // store.dispatch({type: 'ageAddd'}); // 老的方式
    store.dispatch(actionCreator.ageAdd());
  }
  changeHobby() {
    // store.dispatch({type: 'hobbyAdd', item: 'coding'})
    store.dispatch(actionCreator.hobbyAdd('coding'))
  }
  componentDidMount() {
    this.setState(store.getState())
    // 数据更新，页面没有更新，所以需要订阅数据的变化
    // 添加订阅
    this.un = store.subscribe(()=>{
      // 订阅数据的回调，每当数据更新时都会自动执行
      // console.log(store.getState().age);
      this.setState(store.getState())
    })
  }
  componentWillUnmount () {
    // 取消订阅
    this.un();
  }
  render() {
    console.log(store.getState());
    return (
      <div>
        <p>Redux的使用---1</p>
        <p>年龄：{this.state.age}</p>
        <p>爱好：{
            this.state.hobby.map(((item,index) => {
              return (
                <span key={index}>{item}/</span>
              )
            }))
          }</p>
          <button onClick={()=>this.changeAge()}>年龄+1</button>
          <button onClick={()=>this.changeHobby()}>爱好+1</button>
          <br />
          <NavLink to="/redux2">页面2</NavLink>
      </div>
    )
  }
}
